package com.yang.file.service.impl;

import com.yang.file.service.FileStorageService;
import io.minio.GetObjectArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.RemoveObjectArgs;
import org.springframework.util.StringUtils;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author Billyang
 * @date 2024/9/23 17:22
 */
public class MinIOFileStorageService implements FileStorageService {

    private MinioClient minioClient;

    private String endPoint;

    private String bucket;

    private String readPath;

    public MinIOFileStorageService(String accessKey, String secretKey, String endPoint, String bucket, String readPath) {
        this.minioClient = MinioClient.builder().credentials(accessKey, secretKey).endpoint(endPoint).build();
        this.bucket = bucket;
        this.readPath = readPath;
        this.endPoint = endPoint;
    }

    private final static String separator = "/";


    /**
     * @param dirPath
     * @param filename yyyy/mm/dd/file.jpg
     * @return
     */
    public String builderFilePath(String dirPath, String filename) {
        StringBuilder stringBuilder = new StringBuilder(50);
        if (!StringUtils.isEmpty(dirPath)) {
            stringBuilder.append(dirPath).append(separator);
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        String todayStr = sdf.format(new Date());
        stringBuilder.append(todayStr).append(separator);
        stringBuilder.append(filename);
        return stringBuilder.toString();
    }

    @Override
    public String uploadImgFile(String prefix, String filename, InputStream inputStream) {
        String filePath = builderFilePath(prefix, filename);
        try {
            PutObjectArgs putObjectArgs = PutObjectArgs.builder().object(filePath).contentType("image/jpg").bucket(bucket).stream(inputStream, inputStream.available(), -1).build();
            minioClient.putObject(putObjectArgs);
            StringBuilder urlPath = new StringBuilder(readPath);
            urlPath.append(separator + bucket);
            urlPath.append(separator);
            urlPath.append(filePath);
            return urlPath.toString();
        } catch (Exception ex) {
            throw new RuntimeException("上传文件失败");
        }
    }

    @Override
    public String uploadHtmlFile(String prefix, String filename, InputStream inputStream) {
        String filePath = builderFilePath(prefix, filename);
        try {
            PutObjectArgs putObjectArgs = PutObjectArgs.builder().object(filePath).contentType("text/html").bucket(bucket).stream(inputStream, inputStream.available(), -1).build();
            minioClient.putObject(putObjectArgs);
            StringBuilder urlPath = new StringBuilder(readPath);
            urlPath.append(separator + bucket);
            urlPath.append(separator);
            urlPath.append(filePath);
            return urlPath.toString();
        } catch (Exception ex) {
            throw new RuntimeException("上传文件失败");
        }
    }

    @Override
    public void delete(String pathUrl) {
        String key = pathUrl.replace(endPoint + "/", "");
        int index = key.indexOf(separator);
        //根据上面上传图片返回的地址，反向拆解出来的
        String bucket = key.substring(0, index);
        String filePath = key.substring(index + 1);
        // 删除Objects
        RemoveObjectArgs removeObjectArgs = RemoveObjectArgs.builder().bucket(bucket).object(filePath).build();
        try {
            minioClient.removeObject(removeObjectArgs);
        } catch (Exception e) {
            throw new RuntimeException("删除文件失败");
        }
    }

    @Override
    public byte[] downLoadFile(String pathUrl) {
        String key = pathUrl.replace(endPoint + "/", "");
        int index = key.indexOf(separator);
        String bucket = key.substring(0, index);
        String filePath = key.substring(index + 1);
        InputStream inputStream = null;
        try {
            inputStream = minioClient.getObject(GetObjectArgs.builder().bucket(bucket).object(filePath).build());
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buff = new byte[100];
            int rc = 0;
            while (true) {
                if (!((rc = inputStream.read(buff, 0, 100)) > 0)) break;
                byteArrayOutputStream.write(buff, 0, rc);
            }
            return byteArrayOutputStream.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("下载文件失败");
        }
    }

    public static void main(String[] args) throws FileNotFoundException {
        MinIOFileStorageService fileStorageService = new MinIOFileStorageService("minio", "minio123",
                "http://192.168.88.131:9000", "leadnews",
                "http://192.168.88.131:9000");
        FileInputStream fileInputStream = new FileInputStream("e:\\vue_basic.html");
        String filePath = fileStorageService.uploadHtmlFile("", "vue_basic.html", fileInputStream);
        System.out.println(filePath);
    }
}
